package com.example.service.impl;

import com.example.mapper.UserMapper;
import com.example.pojo.DTO.*;
import com.example.pojo.VO.Result;
import com.example.pojo.VO.UserBaseDataVO;
import com.example.pojo.entrity.Users;
import com.example.service.UserService;
import com.example.utils.CreateID;
import com.example.utils.JwtUtil;
import com.example.utils.Md5Util;
import com.example.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class UserServiceImpl implements UserService  {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result add(RegisterUser user) {

//        判断俩次密码是否相同
        if(user.getPassword().equals(user.getReplacePassword()))
        {
//            TODO 从redis中拿到数据比对验证码是否正确
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String code= (String) valueOperations.get("code");
            if(code.equals(user.getCode()))
            {
                Users users=new Users();
//            生成id
                users.setUserId(CreateID.createUniqueID());
//            密码加密
                users.setPassword(Md5Util.getMD5String(user.getPassword()));
                users.setEmail(user.getEmail());
                userMapper.insert(users);
                return Result.success("注册成功");
            }
            return Result.error("验证码不正确");

        }
        return Result.error("密码不相同");

    }

    @Override
    public Result UserLogin(LoginDTO loginDTO) {
//        查找用户是否存在
        log.info("数据检查{}",loginDTO.getUserId());
        Users users=userMapper.findById(loginDTO.getUserId());
        log.info("数据检查{}",users);
        if(users!=null)
        {
            log.info("数据检查2");
//            String pwd=Md5Util.getMD5String(loginDTO.getPassword());
            String pwd=loginDTO.getPassword();
            if(pwd.equals(users.getPassword()))
            {
                Map<String ,Object> claims=new HashMap<>();
                claims.put("userId",users.getUserId());
                claims.put("email",users.getEmail());
//                根据用户id和email生成token
                String token= JwtUtil.getToken(claims);
//               TODO 将token存储到redis中,将当前用户也存储到redis中后期进行其他添加，或者直接添加到Thread中
                ValueOperations<String,String>operations= redisTemplate.opsForValue();
//                设置token过期时间
                operations.set("token",token,1,TimeUnit.HOURS);
//                登录的时候将用户对象存储到redis中
                ValueOperations p=redisTemplate.opsForValue();
                p.set("userId",users.getUserId());
                p.set("email",users.getEmail());
                return Result.success(token);
            }
            return Result.error("账户名或密码不正确");
        }
        return Result.error("账户名或密码不正确");
    }

    @Override
    public Result updatePwd(UpdatePwdDTO pwdDTO) {
        Map<String,Object>map= ThreadLocalUtil.get();
        String UserId= (String) map.get("userId");
        Users users=userMapper.findById(UserId);
        if(Md5Util.getMD5String(pwdDTO.getOlderPwd()).equals(users.getPassword()))
        {
            userMapper.updatePwd(Md5Util.getMD5String(pwdDTO.getNewPwd()),UserId);
            return Result.success("密码修改成功");

        }
        return Result.error("原密码不正确");
    }

    @Override
    public Result updateEamil(String email,String code) {
//        从redis中获取验证码
        String cd="code";
        ValueOperations<String,String>operations=redisTemplate.opsForValue();
        String redisCode=operations.get(cd);
        if(code.equals(redisCode))
        {
            //        获取当前登录用户
            Map<String,Object>map=ThreadLocalUtil.get();
            String userId= (String) map.get("userId");
            Users users=userMapper.findById(userId);
            userMapper.updateEmail(users.getUserId(),email);
            return Result.success("修改成功");
        }

        return Result.error("验证码不正确");
    }

    @Override
    public Result updateBase(UpdateBaseDTO baseDTO) {
        //        通过redis获取当前用户的信息
       ValueOperations operations=redisTemplate.opsForValue();
       String userId= (String) operations.get("userId");
        userMapper.updateBase(userId,baseDTO);
        return Result.success("修改成功");
    }

    @Override
    public Result updateAvater(String avater) {
//       TODO 从阿里云上获取储存的图片地址
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avater,id);
        return Result.success("跟新成功");
    }

    @Override
    public Result codeLogin(String code,String email) {
        Users users=userMapper.findByEmail(email);
        if(users!=null)
        {
//            生成jwt令牌
            Map<String ,Object> claims=new HashMap<>();
            claims.put("userId",users.getUserId());
            claims.put("email",users.getEmail());
//                获取生成的token
            String token= JwtUtil.getToken(claims);
//                将token存储到redis中
            ValueOperations<String,String>operations= redisTemplate.opsForValue();

//                设置token过期时间
            operations.set(token,token,1, TimeUnit.HOURS);

            return Result.success(token);

        }
        return Result.error("该用户不存在");
    }

    @Override
    public Result codeUpdatePwd(CodeUpdatePwdDTO codeUpdatePwdDTO) {
//        TODO 从redis中将验证码取出来

        return null;
    }

    @Override
    public Result getData() {
//          从redis中获取数据
        ValueOperations operations=redisTemplate.opsForValue();
        String userId= (String) operations.get("userId");
        Users users=userMapper.findById(userId);
        UserBaseDataVO userBaseDataVO =new UserBaseDataVO(users.getAvatar(),users.getAddress()
                ,users.getAge()
                ,users.getNickname(),users.getSex(),users.getPhone(),users.getEmail());

        return Result.success(userBaseDataVO);
    }

}
